package de.mhu.mandalaui.impl;

import java.io.PrintWriter;

import javax.servlet.ServletResponse;

import de.mhu.mandalaui.Response;
import de.mhu.mandalaui.Ui;
import de.mhu.mandalaui.Window;
import de.mhu.mandalaui.remote.RemoteRegistry;

public class DefaultWindow extends Window implements WindowExtended {

	public DefaultWindow(Ui ui, String id) {
		super(ui, id);
		ui.add(this);
	}

	@Override
	protected void doInitialize() {
		
	}

	@Override
	protected void doDestroy() {
		
	}

	@Override
	public void doRender(Object... attributes) throws Exception {
		PrintWriter writer = null;
		for (Object attribute : attributes) {
			if (attribute instanceof javax.servlet.ServletResponse)
				writer = ((ServletResponse) attribute).getWriter();
			else
			if (attribute instanceof PrintWriter)
				writer = (PrintWriter) attribute;
		}
		
		DefaultResponse resp = new DefaultResponse(this, writer);
		render(resp);
	}

	public void render(Response response) {
		response.startTag("div", "container", this);
		super.render(response);
		((DefaultResponse)response).renderAttributes();
		
		response.endTag("div");
	}

	@Override
	public String getRemoteUrl(RemoteRegistry registry) {
		return "http://localhost:8080/MandalaUi01/MandalaDemo?_mandala_action=" + getId() + "." + registry.getCallable().getId();
	}

	@Override
	public void beforeRemoteCall(PrintWriter out, String string) {
		if (getWindow().getUi().isDebugRemoteCalls())
			out.println("if (console) console.log('request: ' + "+string+");");
	}

	@Override
	public void afterRemoteCall(PrintWriter out, String string) {
		if (getUi().isDebugRemoteCalls())
			out.println("    if (console) console.log('response: ' + JSON.stringify("+string+"));");
	}
	
}
